﻿using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

using Sustainalytics.ClientDW.Entities;
using Sustainalytics.ESG.Entities;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using Sustainalytics.Utils;

using Sustainalytics.Utils.WebApi.ErrorCodes;
using System.Web.Http.Cors;
using Sustainalytics.MongoDB.Extensions;
using MongoDB.Driver;
using System.Threading.Tasks;

namespace Sustainalytics.ESGRatings.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    //[AutoInvalidateCacheOutput]
    [LogControllerFilter(true, true, false)] 
    [RoutePrefix("api/v1/company")]
    public class EsgIndustryLeadPersonnelPhotoController : ApiController
    {

        public EsgIndustryLeadPersonnelPhotoController()
        {
            Setup();
        }

        public EsgIndustryLeadPersonnelPhotoController(OnlineReportAnalystBusinessLogicUnit service)
        {
            _service = service;
        }


       // [CacheOutput(ServerTimeSpan = 100, ClientTimeSpan = 0, NoCache = true, MustRevalidate = true, Private = true)]
        [Route("{companyId}/esgIndustryLeadPersonnel/Photo")]
       
        public async Task<HttpResponseMessage> Get(Guid companyId, [FromUri]int[] universeIds = null)
        {
        
            try
            {
                var data = await _service.GetImage(companyId);
                var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new ByteArrayContent(data)};
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                return result;
            }
            catch (ESGReasearchNotFoundException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message

                });

            }
            catch (ESGReasearchNotInUniversesException ex)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound, new
                {
                    errCode = ex.GetType().ToString(),
                    message = ex.Message

                });
            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
        }


        private OnlineReportAnalystBusinessLogicUnit _service;


        private void Setup()
        {

            IMongoCollection<Analyst> repository = MongoFactory.GetCollectionFromDatabase<Analyst>(ClientDWConnection.GetConnectionString());

            IMongoCollection<CorporateData> corporateDataRepository = MongoFactory.GetCollectionFromDatabase<CorporateData>(ClientDWConnection.GetConnectionString());

            IMongoCollection<RPCompanyProfile> rpCompanyProfileRepository = MongoFactory.GetCollectionFromDatabase<RPCompanyProfile>(ClientDWConnection.GetConnectionString());


            _service = _service ?? new OnlineReportAnalystBusinessLogicUnit(repository, corporateDataRepository, rpCompanyProfileRepository);
        }
    }
}
